//
//  ViewController.m
//  NSOupputStreanDeom
//
//  Created by MyMac on 15/11/2.
//  Copyright © 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"
#import <Foundation/Foundation.h>
@interface ViewController ()<NSStreamDelegate>
@property(nonatomic,strong)NSMutableData*data;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString*str=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString*path=[str stringByAppendingPathComponent:@"3iiii49943555ooo.png"];
    NSLog(@"%@",path);
    NSString*strP=[[NSBundle mainBundle]pathForResource:@"屏幕快照 2015-11-02 下午5.09.05.png" ofType:nil];
    _data=[NSMutableData dataWithContentsOfFile:strP];
    NSOutputStream*output=[[NSOutputStream alloc]initToFileAtPath:path append:YES];
   // NSOutputStream*output=[[NSOutputStream alloc]initWithURL:[NSURL URLWithString:@"120.27.45.244"] append:NO];
    output.delegate=self;
    [output scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [output open];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}
static NSInteger i=0;
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
    
    switch (eventCode) {
        case NSStreamEventHasSpaceAvailable:{
         NSOutputStream*stream=(NSOutputStream*)aStream ;
            NSInteger len=0;
            if (_data.length-(i+1)>=1024) {
                len=1024;
            }else{
                len=_data.length-(i+1);
            }
            //分段写入
            NSData*current=[_data subdataWithRange:NSMakeRange(i, len)];
       
            i+=len;
       NSUInteger count=[stream write:( const uint8_t*)[current bytes] maxLength:len];
            NSLog(@"%ld",count);
        }
            break;
         case NSStreamEventEndEncountered:
            NSLog(@"写入文件完成");
            [aStream close];
            [aStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            break;
        default:
            break;
    }





}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
